let utils = require('../../../utils/util.js')
let WxParse = require('../../../utils/wxParse/wxParse.js');
let network = require("../../../utils/requestManager.js")
let app = getApp()
/**
* WxParse.wxParse(bindName , type, data, target,imagePadding)
* 1.bindName绑定的数据名(必填)
* 2.type可以为html或者md(必填)
* 3.data为传入的具体数据(必填)
* 4.target为Page对象,一般为this(必填)
* 5.imagePadding为当图片自适应是左右的单一padding(默认为0,可选)
*/
Page({

  /**
   * 页面的初始数据
   */
  data: {
    image_url:'',
    price:'',
    limit_number:'',
    apply_people_number:'',
    product_status:'',
    title: "",    
    start_time: "",
    end_time: "",
    activity_flow:"",
    content:" ",
    countDownData: {
      "isOver": false,
      "activity_time": "2019-10-22T09:12:43.083Z",
    },
    activity_detail:'',
    phone:"",
    id:'',
    shop_id:"",
    hidden:true,
    sign_disable:true,
    user_activity_status:"立即报名",
    qrcode_path:"",//二维码路径
    user_phone:false//判断用户手机号，true有，false没有
  },

  /**
   * 生命周期函数--监听页面加载
   * Id为跳转传递的参数
   */
  onLoad: function(options) {
    console.log("转发options")
    console.log(options)
    let that = this;
    
    //获取二维码传入的scene
    let scene = decodeURIComponent(options.scene);
    console.log(scene)
    console.log("扫码=================================scene")
    if(scene == 'undefined'){//页面进入
      //更新转发传入进来的id
      if(options.shop_id){
        console.log("有shop_id")
        app.globalData.shop_id = options.shop_id//更新shop_id
        that.setData({
          id:options.activity_id
        })
      }else{//点击活动列表进入
        console.log("=========无shop_id==================")
        that.setData({
          id: options.activity_id
        })
      }
      /**
       * 请求数据
       * **/
      requestWeiActivity(that)
    }else{//扫码进入
      console.log("扫码进入的")
      network.getSceneFromMiniCodeBySceneID(scene, function (res) {
        console.log("扫码====================res")
        console.log(res)
        app.globalData.shop_id = res.detail.shop
        that.setData({
          id:res.detail.id
        })
        console.log(res.detail.id)
        console.log(that.data.id)
        console.log("活动ID================")
        
        /**
         * 请求数据
         * **/
          requestWeiActivity(that)
      })
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage:function(res){
    let that = this;
    let activity_id = that.data.id
    let shop_id = that.data.shop_id
      console.log(shop_id)
      return {
        title: that.data.title,//当前小程序名称
        imageUrl: that.data.image_url,
        path: "/pages/showView/signUp/weiActivity?activity_id=" + activity_id + '&shop_id=' + shop_id,
        success: function (ress) {
          wx.showToast({
            title: '转发成功',
            duration: 2000
          })
        },
        fail: function (err) {
          wx.showToast({
            title: '转发失败',
            icon: "none"
          })
        }
      }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    console.log("xiala")
    requestWeiActivity(this)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  
 
  /**
   * 点击跳转首页
   * **/
  to_home: function (res) {
    console.log("res")
    wx.navigateTo({
      url: '/pages/index/index',
      success: function (res) { },
      fail: function (res) { },
      complete: function (res) { },
    })
  },

  /**
   * 点击跳转分享
   * **/
  to_share: function (e) {
    let that = this
    console.log(e)
    console.log("活动ID和shopID")
    console.log(that.data.shop_id)
    console.log(that.data.id)
    /**
     * 自定义封装scene
     * 扫码携带
     * **/
    network.ownerShare(function (shop_id) {
      console.log(shop_id)
      //请求二维码接口
      network.postRequest('xcx/create/qrcode', {
        page: "pages/showView/signUp/weiActivity",
        shop: shop_id,
        id: that.data.id,
        type: 1,
        width: "100"
      }, function (res) {
        console.log(res)
        console.log("请求二维码成功")
        // console.log(res.detail.path)
        //请求二维码图片先缓存在本地
        wx.getImageInfo({
          src: res.detail.path,
          success: function (ress) {
            console.log("获取图片信息成功")
            console.log(ress)
            that.setData({
              qrcode_path: ress.path
            })

            //请求成功之后跳转
            console.log(res)
            let activity_id = e.currentTarget.dataset.id;
            let qrcode_path = that.data.qrcode_path;
            console.log("二维码")
            console.log(qrcode_path)
            wx.navigateTo({
              url: '/pages/showView/signUp/shareActivity?id=' + activity_id + "&qrcode=" + qrcode_path,
            })
          },
          fail: function (err) {
            console.log("err")
            wx.showToast({
              title: '图片生成失败',
              icon: "none"
            })
          }
        })
      })
    })
   },

  /**
   * 点击跳转电话
   * **/
  to_phone: function (res) {
    let that = this;
    let user_phone = that.data.phone
    console.log(user_phone)
    if (user_phone == "" || user_phone == undefined){
      wx.showToast({
        title: '手机号码为空',
        icon:"none"
      })
    }else{
      wx.makePhoneCall({
        phoneNumber: user_phone,
      })
    }
  },

  /**
   * 点击立即报名
   * **/
  signUpBtn:function(){
    let that = this;
    console.log("dianji ")
    let user_no_phone = that.data.user_phone
    if(user_no_phone == false){//没有手机号
      wx.showModal({
        title: '提示',
        content: "需要绑定手机号",
        showCancel: false,
        success(ress) {
          console.log(ress)
          if (ress.confirm) {
            console.log('用户点击确定')
            that.setData({
              hidden: false
            })
          } else {
            console.log('用户点取消')
          }
        },
        complete(res) {
          console.log(res)
        }
      })
    }else{
      let that = this;
      let activity_id = that.data.id
      network.postRequest('/apply/people/create?id=' + activity_id,{},function(res){
        console.log(res)
        that.setData({
          sign_disable:true,
          user_activity_status:"已报名"
        })
        //报名成功
        wx.showModal({
          title: '提示',
          content: '您的报名信息已提交，请记得在活动时间内到店参加活动哦！',
          showCancel: false,
          confirmColor: "#F09D3E"
        })
      })
    }
  },
  /**
   * 绑定手机号输入框
   * **/
  bind_phone_input:function(e){
    console.log(e)
    let that = this;
    that.setData({
      bind_phone:e.detail.value
    })    
  },
  /**
   * 提交用户绑定手机号
   * **/
  bind_user_phone:function(e){
    let that = this;
    let activity_id = that.data.id
    let reg = /1[\d]{10}/;
    let phone = this.data.bind_phone;
    if (!phone) {
      wx.showToast({
        title: '请填写手机号！',
        icon: 'none'
      })
      return;
    }
    if (!reg.test(phone)) {
      wx.showToast({
        title: '请填写正确的手机号！',
        icon: 'none'
      })
      return;
    }
    /**
     * 提交手机号
     * **/
    network.postRequest('/apply/people/create?id=' + activity_id,{phone:phone},function(res){
      console.log(res)
      that.setData({
        hidden:true,
        sign_disable: true,
        user_activity_status: "已报名"
      })
    })
  }
})

function requestWeiActivity(that){
  //请求数据
  let activity_id = that.data.id
  console.log(activity_id)
  console.log("扫码扫码扫码扫码扫码")
  network.getRequest('apply/little/apply/product/detail?id=' + activity_id, {}, function (res) {
    console.log(res)
    let activity_status = res.detail.product.product_status;//活动状态
    let user_sign_activity = res.detail.apply
    console.log(user_sign_activity)
    
    let countdown_data = {}
    if (activity_status == 1) {//未开始
      countdown_data["isOver"] = false
      countdown_data["activity_time"] = res.detail.product.start_time
      that.setData({
        user_activity_status: "活动未开始"
      })
    } else if (activity_status == 2) {//进行中
      countdown_data["isOver"] = false
      countdown_data["activity_time"] = res.detail.product.end_time
      if (user_sign_activity == true) {
        that.setData({
          sign_disable: true,
          user_activity_status: "已报名"
        })
      }else{
        that.setData({
          sign_disable: false
        })
      }
    } else {//已结束
      countdown_data["isOver"] = true
      countdown_data["activity_time"] = ""
      that.setData({
        user_activity_status: "活动已结束",
      })
    }
    //匹配换行符
    let desc = res.detail.product.desc.replace(/\n|\r\n/g, '\n');
    //格式化时间
    let activity_start_time = utils.formatUTCDate(res.detail.product.start_time);
    console.log(activity_start_time)
    let activity_end_time = utils.formatUTCDate(res.detail.product.end_time);
    //json字符串转换为数组
    let activity_detail_arr = JSON.parse(res.detail.product.detail_product)
    console.log(JSON.parse(res.detail.product.detail_product))
    console.log(generateDescListByList(activity_detail_arr))
    that.setData({
      image_url: res.detail.product.image_url,
      price: res.detail.product.price / 100,
      limit_number: res.detail.product.limit_number,
      apply_people_number: res.detail.product.apply_people_number,
      product_status: res.detail.product.product_status,
      title: res.detail.product.title,
      activity_flow: desc,
      start_time: activity_start_time,
      end_time: activity_end_time,
      countDownData: countdown_data,
      activity_detail: activity_detail_arr,
      id: res.detail.product.id,
      shop_id: res.detail.product.shopId,
      phone: res.detail.product.shop_phone,
      bind_phone: '',
      user_phone: res.detail.click,
    })
  })
}


///根据请求到的详情描述数组生成可用的数据
function generateDescListByList(array) {
  var temp = []
  if (array.length == 0) {
    temp.push({
      type: 'image',
      imagePath: '',
      imageName: '',
      text: '',
      first: true
    })
  } else {
    for (var i = 0; i < array.length; i++) {
      var item = array[i]
      var descItem = {
        type: item.image != "" && item.image != undefined ? "image" : "text",
        imagePath: item.image,
        imageName: item.image,
        text: item.content,
        first: i == 0 ? true : false,
        last: i == array.length - 1 ? true : false
      }
      temp.push(descItem)
    }
  }
  console.log(temp)
  return temp
}